<template>
  <div class="resident-management-container">
    <!-- 使用卡片组件包裹主要内容 -->
    <el-card class="box-card">
      <div slot="header" class="custom-header">
        <h2 class="page-title">居民管理</h2>
      </div>

      <!-- 筛选/搜索区域 - 居中显示 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="demo-form-inline filter-form">
          <el-form-item label="搜索类型:">
            <el-select v-model="filters.searchType" placeholder="请选择搜索类型" style="width: 100px;">
              <el-option
                  v-for="item in searchOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="关键词:">
            <el-input v-model="filters.keyword" placeholder="请输入搜索关键词"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 - 右对齐 -->
      <div class="action-buttons">
        <!-- 新增居民档案按钮已移除 -->
        <el-button type="success" icon="el-icon-download" @click="handleExport" :loading="exportLoading">
          {{ exportLoading ? '导出中...' : '导出居民档案' }}
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
          :data="tableData"
          style="width: 100%; margin-top: 20px;"
          border
          v-loading="loading"
      >
        <el-table-column
            prop="residentId"
            label="居民编号"
            width="100"
            align="center">
        </el-table-column>
        <el-table-column
            prop="name"
            label="姓名"
            width="120"
            align="center">
        </el-table-column>
        <el-table-column
            prop="idCard"
            label="身份证号"
            width="200"
            align="center">
        </el-table-column>
        <el-table-column
            prop="phoneNumber"
            label="手机号码"
            width="150"
            align="center">
        </el-table-column>
        <el-table-column
            label="用户标签"
            align="center">
          <template #default="scope">
            <el-tag
                v-for="tag in scope.row.diseases"
                :key="tag"
                class="user-tag">
              {{tag}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="250"
            align="center">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row.residentId)">编辑详情</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row.residentId)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row.residentId)" style="color: #F56C6C;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 - 居中显示 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>

      <!-- 弹窗组件 -->
      <residents-detail
          v-if="dialogVisible"
          :visible="dialogVisible"
          :details="details"
          :health-record="healthRecord"
          @update:visible="dialogVisible = $event"
      />
      <residents-edit
          v-if="editDialogVisible"
          :visible="editDialogVisible"
          :details="editDetails"
          :isEdit="true"
          @update:visible="editDialogVisible = $event"
          @submit-success="handleEditSuccess"
      />

    </el-card>
  </div>
</template>

<script>
import {deleteResident, queryAllDetails, queryAllShow, queryByResidentId} from "../api/Residents.js";
import ResidentsEdit from "../components/ResidentsEdit.vue";
import ResidentsDetail from "../components/ResidentsDetail.vue";
import {exportResidents} from "../api/ExportExcel.js";

export default {
  name: 'ResidentsList',
  components: {ResidentsDetail,ResidentsEdit},
  data() {
    return {
      total:0,
      pageNum:1,
      pageSize:5,

      dialogVisible: false,
      editDialogVisible: false,
      exportLoading: false,
      details: [],
      editDetails:{},
      healthRecord:{},
      filters: {
        searchType: 'all',
        keyword: ''
      },
      // 搜索选项数据
      searchOptions: [
        { label: '全文', value: 'all' },
        { label: '居民编号', value: 'residentId' },
        { label: '姓名', value: 'name' },
        { label: '手机号', value: 'phoneNumber' },
        { label: '标签', value: 'tag' }
      ],
      loading: false,
      tableData: [
        {
          residentId:'',
          name: '',
          phoneNumber:'',
          idCard: '',
          diseases:[]
        }
      ]
    };
  },
  methods: {
    handleSizeChange(newSize){
      this.pageSize = newSize;
      this.loadResidents();
    },
    handleCurrentChange(newPage){
      this.pageNum = newPage;
      this.loadResidents();
    },
    handleEditSuccess() {
      this.loadResidents();
    },
    handleSearch() {
      console.log('正在搜索:', this.filters);
      this.loading = true;
      // 模拟API调用
      setTimeout(() => {
        this.loading = false;
        this.$message({
          message: '查询成功！',
          type: 'success'
        });
      }, 1000);
    },
    resetSearch() {
      this.filters = {
        searchType: 'all',
        keyword: ''
      }
      this.$message({
        message: '搜索条件已重置',
        type: 'info'
      });
      this.loadResidents();
    },
    async handleExport() {
      this.exportLoading = true;
      this.$message.info('开始导出居民档案...');

      try {
        // 注意：这里不再解构 {data:data}，而是获取整个响应对象 response
        // 同时传递 responseType: 'blob' 配置给 axios
        const response = await exportResidents(this.pageNum, this.pageSize);

        // 检查响应状态 (虽然是 axios 封装的，但检查一下总没错)
        if (response.status === 200) {
          // 从响应中获取 Blob 数据
          const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel MIME type
          });

          // --- 创建下载链接并触发下载 ---
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          // 从响应头 Content-Disposition 中尝试获取文件名 (如果后端设置了的话)
          // 如果没有设置或难以解析，可以使用默认文件名
          let fileName = '居民数据.xlsx'; // 默认文件名
          const disposition = response.headers['content-disposition'];
          if (disposition && disposition.indexOf('attachment') !== -1) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) {
              // 尝试解码文件名 (应对 URLEncoder.encode)
              try {
                fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''));
              } catch (e) {
                fileName = matches[1].replace(/['"]/g, '');
              }
            }
          }
          link.setAttribute('download', fileName); // 设置下载文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url); // 释放 URL 对象
          // --- 下载完成 ---
          this.$message.success('居民档案导出成功！');
        } else {
          this.$message.error('导出失败，服务器响应异常。');
        }
      } catch (error) {
        console.error('导出居民档案时出错:', error);
        this.$message.error('导出居民档案时发生错误: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    },
    async handleEdit(id) {
      this.$message.info(`正在编辑居民: ${id}`);
      let {data:data} = await queryByResidentId(id)
      this.editDetails = data.data;
      console.log(this.editDetails)
      this.editDialogVisible = true;
    },
    async handleView(id) {
      this.$message.info(`正在查看居民: ${id}`);
      let{data:data} = await queryAllDetails(id)
      console.log(data)
      this.details = data.data;
      this.dialogVisible = true;
    },
    handleDelete(id) {
      this.$confirm(`此操作将永久删除居民 "${id}", 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        let {data:data} = deleteResident(id)
        this.loadResidents();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async loadResidents(){
      let {data:data} = await queryAllShow(this.pageNum,this.pageSize)
      console.log(data)
      this.tableData = data.data.list.sort((a, b) => {
        return a.residentId - b.residentId;
      });
      this.total = data.data.total;
    }
  },
  mounted() {
    this.loadResidents()
  }
};
</script>

<style scoped>
.resident-management-container {
  padding: 20px;
  background-color: #f5f7fa; /* 可选：给页面背景一点颜色 */
}

/* 自定义卡片头部样式 */
.custom-header {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 15px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 渐变背景 */
  border-radius: 4px 4px 0 0; /* 与卡片圆角匹配 */
  margin: -20px -20px 20px -20px; /* 负边距使其撑满卡片头部 */
}

.page-title {
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.3); /* 添加文字阴影 */
}

/* 搜索区域居中 */
.filter-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap; /* 允许表单项换行 */
  align-items: flex-end; /* 底部对齐 */
  gap: 15px; /* 表单项之间的间距 */
}

.filter-form .el-form-item {
  margin-bottom: 0; /* 移除默认底部外边距 */
}

/* 操作按钮区域 - 右对齐 */
.action-buttons {
  display: flex;
  justify-content: flex-end; /* 水平靠右 */
  margin-bottom: 20px;
}

/* 表格上方的标签样式 */
.user-tag {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
  margin-right: 5px;
}

/* 分页容器样式 - 居中 */
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin-top: 20px; /* 与表格的间距 */
  margin-bottom: 10px; /* 与卡片底部的间距 */
}

/* 美化分页组件 */
.pagination-container ::v-deep .el-pagination {
  padding: 10px 0; /* 内边距 */
  border-radius: 4px; /* 圆角 */
  /* 可以根据需要添加背景色 */
  /* background-color: #f0f2f5; */
}

.pagination-container ::v-deep .el-pagination .el-pager li {
  background-color: #fff; /* 默认页码背景色 */
  border: 1px solid #dcdfe6; /* 边框 */
  color: #606266; /* 字体颜色 */
  min-width: 30px; /* 最小宽度 */
  height: 30px; /* 高度 */
  line-height: 30px; /* 行高 */
  margin: 0 2px; /* 左右间距 */
  border-radius: 2px; /* 小圆角 */
  transition: all 0.3s; /* 过渡效果 */
}

.pagination-container ::v-deep .el-pagination .el-pager li:hover {
  color: #409eff; /* 悬停字体颜色 */
  border-color: #409eff; /* 悬停边框颜色 */
}

.pagination-container ::v-deep .el-pagination .el-pager li.active {
  background-color: #409eff; /* 激活状态背景色 */
  border-color: #409eff; /* 激活状态边框颜色 */
  color: #fff; /* 激活状态字体颜色 */
}

.pagination-container ::v-deep .el-pagination button {
  background-color: #fff; /* 按钮背景色 */
  border: 1px solid #dcdfe6; /* 按钮边框 */
  color: #606266; /* 按钮字体颜色 */
  min-width: 30px; /* 最小宽度 */
  height: 30px; /* 高度 */
  line-height: 30px; /* 行高 */
  border-radius: 2px; /* 小圆角 */
  transition: all 0.3s; /* 过渡效果 */
  padding: 0 5px; /* 左右内边距 */
}

.pagination-container ::v-deep .el-pagination button:hover {
  color: #409eff; /* 悬停字体颜色 */
  border-color: #409eff; /* 悬停边框颜色 */
}

.pagination-container ::v-deep .el-pagination button:disabled {
  color: #c0c4cc; /* 禁用状态字体颜色 */
  background-color: #fff; /* 禁用状态背景色 */
  border-color: #ebeef5; /* 禁用状态边框颜色 */
}

.pagination-container ::v-deep .el-pagination .el-pagination__sizes .el-select .el-input .el-input__inner {
  height: 30px; /* 下拉框高度 */
  line-height: 30px; /* 下拉框行高 */
  border-radius: 2px; /* 下拉框圆角 */
  padding: 0 10px; /* 下拉框内边距 */
  font-size: 13px; /* 字体大小 */
}

.pagination-container ::v-deep .el-pagination .el-pagination__jump .el-input .el-input__inner {
  height: 30px; /* 输入框高度 */
  line-height: 30px; /* 输入框行高 */
  border-radius: 2px; /* 输入框圆角 */
  padding: 0 10px; /* 输入框内边距 */
  font-size: 13px; /* 字体大小 */
  width: 50px; /* 输入框宽度 */
}


/* 清除浮动（如果需要） */
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>




